package com.wy.controller;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.wy.feignclient.CourseClient;
import com.wy.pojo.Course;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wuyue
 * @date 2020/1/8 15:12
 */
@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallBack")
public class ConsumerController {

     @Autowired
     private RestTemplate restTemplate;

     @Autowired
     private DiscoveryClient discoveryClient;
     @Autowired
     private CourseClient courseClient;
/*  1.未使用eruka服务注册中心
         @GetMapping("/{name}")
     public List<Course> getCourses(@PathVariable String name){
             String url="http://localhost:9090/course/"+name;
            return    restTemplate.getForObject(url,List.class);
     }    */

  //2.现在从服务列表中获取
   /*  @GetMapping("/{name}")
     public List<Course> getCourses(@PathVariable String name){
         ServiceInstance serviceInstance = discoveryClient.getInstances("user-service").get(0);
              String url="http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/course/"+name;
         return    restTemplate.getForObject(url,List.class);
     }*/

    //3. 使用ribbon获取服务（负载均衡） 服务列表的格式为{"user-service":{"ip+port":服务实体：服务实体中有接口}}
    /* @GetMapping("/{name}")
     @HystrixCommand //熔断器
     public List getCourses(@PathVariable String name){
              String url="http://user-service/course/"+name;
         return restTemplate.getForObject(url,List.class);

     }*/

    //4.feign伪装rest请求不在拼接url 编写接口客户端，动态代理接口方式访问传统controller
               @GetMapping("/{name}")
          public  List<Course> findAllByName(@PathVariable String name){
                  return courseClient.findByName(name);
          }

    /* public List getCoursesFallBack(String name){
         log.error("查询用户信息失败"+name);
          List list=new ArrayList();
          list.add("网络太拥挤，请稍后再试");
         return list;
     }*/
       //降级跳转
     public List defaultFallBack(){
         List list=new ArrayList();
         list.add("网络太拥挤，请稍后再试!");
         return list;
     }
}
